package fr.afcepf.atod11.framework.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tools.MyBeanPopulate;

import exceptions.FWHomeValidationException;
import fr.afcepf.atod11.framework.controller.interfaces.IAction;
import fr.afcepf.atod11.framework.forms.LoginForm;
import fr.afcepf.atod11.framework.forms.interfaces.IActionForm;

/**
 * Servlet implementation class ActionServlet
 */
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Factory factory;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ActionServlet() {
		super();

		factory = new Factory();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String configPath = getServletContext().getRealPath(
				"/WEB-INF/framework.xml");

		if (factory.parseConfig(configPath)) {
			System.out.println("on passe dans action servlet");
			System.out.println(request.getServletPath());
			IAction action = factory.resolve(request.getServletPath());
			IActionForm actionForm = factory.getForm(request.getServletPath());
			MyBeanPopulate.populateBeanWilfried(actionForm, request.getParameterMap());
			// on valide le formulaire
			boolean result = actionForm.validate();
			if (result) {
				action.setActionForm(actionForm);
				action.execute(request, response);
			} else
				throw new FWHomeValidationException(
						"erreur de validation loginForm");

		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
